import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import '../services/constants.dart';
import '../services/token_manager.dart';
import 'package:image_picker/image_picker.dart';
import 'package:dio/dio.dart';
import '../services/market_events.dart';

class PublishProductScreen extends StatefulWidget {
  @override
  State<PublishProductScreen> createState() => _PublishProductScreenState();
}

class _PublishProductScreenState extends State<PublishProductScreen> {
  List<dynamic> categoryList = [];
  int selectedCategoryId = 0;
  String selectedCategoryName = '';
  final _nameController = TextEditingController();
  final _priceController = TextEditingController();
  final _descController = TextEditingController();
  final _addressController = TextEditingController();
  bool isLoading = false;
  String userEmail = '';
  List<String> imageUrls = [];

  @override
  void initState() {
    super.initState();
    _initUser();
  }

  Future<void> _initUser() async {
    final userInfo = await TokenManager.instance.getUserInfo();
    userEmail = userInfo?['email'] ?? '';
    print('📧 当前用户邮箱: $userEmail');
    await _loadCategory();
  }

  Future<Map<String, String>> _buildHeaders() async {
    final headers = <String, String>{
      'Content-Type': 'application/json',
    };
    if (userEmail.isNotEmpty) {
      headers['email'] = userEmail;
    }
    final token = await TokenManager.instance.getToken();
    if (token != null && token.isNotEmpty) {
      headers['Authorization'] = 'Bearer ' + token;
    }
    return headers;
  }

  Future<void> _loadCategory() async {
    setState((){isLoading = true;});
    try {
      final url = Uri.parse('${Constants.serverUrl}goods/getCategoryList');
      print('🔍 请求分类列表: $url');
      final res = await http.get(url, headers: await _buildHeaders());
      print('📦 分类接口响应状态码: ${res.statusCode}');
      print('📦 分类接口响应内容: ${res.body}');
      
      if (res.statusCode == 200) {
        final data = jsonDecode(res.body);
        if (data['code'] == 0 && data['data'] is List && data['data'].isNotEmpty) {
          setState(() {
            categoryList = data['data'];
          });
          print('✅ 分类列表加载成功，共 ${categoryList.length} 个分类');
        } else {
          print('❌ 分类数据格式错误或为空: $data');
        }
      } else {
        print('❌ HTTP请求失败: ${res.statusCode}');
      }
    } catch (e) {
      print('❌ 加载分类异常: $e');
    }
    setState((){isLoading = false;});
  }

  void _submit() async {
    if (_nameController.text.isEmpty || _priceController.text.isEmpty || _descController.text.isEmpty || selectedCategoryId==0 || _addressController.text.isEmpty) {
      ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text('请完整填写所有信息')));
      return;
    }
    if (imageUrls.isEmpty) {
      ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text('请至少上传一张商品图片')));
      return;
    }
    setState((){isLoading=true;});
    try {
      // 统一从本地存储读取邮箱，作为用户唯一标识
      final ui = await TokenManager.instance.getUserInfo();
      userEmail = ui['email'] ?? userEmail;
      if (userEmail.isEmpty) {
        setState((){isLoading=false;});
        ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text('未登录或邮箱缺失，无法发布')));
        return;
      }

      final url = Uri.parse('${Constants.serverUrl}goods/publish');
      final body = {
        'categoryId': selectedCategoryId,
        'name': _nameController.text,
        'price': _priceController.text,
        'goodsDesc': _descController.text,
        'address': _addressController.text,
        'images': imageUrls.join(','),
        // 额外在body中带上邮箱，便于后端直接关联（即使后端主要读header）
        'userEmail': userEmail,
      };
      print('📤 发布商品请求: $url');
      print('📤 发布数据: $body');
      print('📤 请求头: ${await _buildHeaders()}');
      final res = await http.post(url, headers: await _buildHeaders(), body: jsonEncode(body));
      print('📥 发布响应状态码: ${res.statusCode}');
      print('📥 发布响应内容: ${res.body}');
      setState((){isLoading=false;});
      if (res.statusCode == 200) {
        final data = jsonDecode(res.body);
        if (data['code'] == 0) {
          ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text('发布成功!')));
          // 通知市场页刷新
          MarketEvents.instance.notifyChanged();
          Navigator.pop(context, { 'success': true, 'categoryId': selectedCategoryId });
          return;
        } else {
          ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text('发布失败: ${data['msg'] ?? '未知错误'}')));
        }
      } else {
        ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text('发布失败: HTTP ${res.statusCode}')));
      }
    } catch (e) {
      setState((){isLoading=false;});
      print('❌ 发布商品异常: $e');
      ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text('发布失败: $e')));
    }
  }

  Widget _buildImageSelector() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Row(
          children: [
            ElevatedButton.icon(
              icon: Icon(Icons.add_a_photo),
              label: Text('选择图片'),
              onPressed: _pickAndUploadImages,
            ),
            SizedBox(width: 12),
            Text('${imageUrls.length}/9'),
          ],
        ),
        SizedBox(height: 4),
        Wrap(
          spacing: 8,
          children: imageUrls.map((url) => Stack(
            children: [
              ClipRRect(
                borderRadius: BorderRadius.circular(6),
                child: Image.network(url, width: 60, height: 60, fit: BoxFit.cover),
              ),
              Positioned(
                right: 0,
                top: 0,
                child: InkWell(
                  onTap: () {
                    setState(() => imageUrls.remove(url));
                  },
                  child: Icon(Icons.cancel, size: 18, color: Colors.red),
                ),
              ),
            ],
          )).toList(),
        ),
      ],
    );
  }

  Future<void> _pickAndUploadImages() async {
    final picker = ImagePicker();
    final picked = await picker.pickMultiImage(imageQuality: 80);
    if (picked == null || picked.isEmpty) return;
    for (final file in picked.take(9 - imageUrls.length)) {
      final url = await _uploadImage(file.path);
      if (url != null) {
        setState(() => imageUrls.add(url));
      }
    }
  }

  Future<String?> _uploadImage(String path) async {
    try {
      final dio = Dio();
      final formData = FormData.fromMap({'file': await MultipartFile.fromFile(path)});
      final response = await dio.post(
        '${Constants.serverUrl}file/uploadImage',
        data: formData,
        options: Options(
          headers: await _buildHeaders(),
          contentType: 'multipart/form-data',
        ),
      );
      if (response.statusCode == 200 && response.data['code'] == 0) {
        return response.data['data']['url'];
      }
    } catch (e) {
      print('上传图片失败: $e');
      ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text('上传图片失败')));
    }
    return null;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('发布商品')),
      body: isLoading ? Center(child: CircularProgressIndicator()) : Padding(
        padding: const EdgeInsets.all(16.0),
        child: ListView(
          children: [
            TextField(
              controller: _nameController,
              decoration: InputDecoration(labelText: '商品名称'),
            ),
            SizedBox(height: 12),
            TextField(
              controller: _priceController,
              keyboardType: TextInputType.number,
              decoration: InputDecoration(labelText: '商品价格'),
            ),
            SizedBox(height: 12),
            TextField(
              controller: _descController,
              maxLines: 3,
              decoration: InputDecoration(labelText: '商品描述'),
            ),
            SizedBox(height: 12),
            _buildImageSelector(),
            SizedBox(height: 12),
            _buildCategorySelector(),
            SizedBox(height: 12),
            TextField(
              controller: _addressController,
              decoration: InputDecoration(labelText: '商品位置'),
            ),
            SizedBox(height: 30),
            ElevatedButton(
              child: Text('发布'),
              onPressed: _submit,
            )
          ],
        ),
      ),
    );
  }

  Widget _buildCategorySelector() {
    return GestureDetector(
      onTap: () => _showCategoryPicker(),
      child: Container(
        padding: EdgeInsets.symmetric(horizontal: 12, vertical: 16),
        decoration: BoxDecoration(
          border: Border.all(color: Colors.grey[400]!),
          borderRadius: BorderRadius.circular(8),
        ),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            Text(
              selectedCategoryName.isEmpty ? '选择分类' : selectedCategoryName,
              style: TextStyle(
                fontSize: 16,
                color: selectedCategoryName.isEmpty ? Colors.grey[600] : Colors.black,
              ),
            ),
            Icon(Icons.chevron_right, color: Colors.grey[600]),
          ],
        ),
      ),
    );
  }

  void _showCategoryPicker() {
    if (categoryList.isEmpty) {
      ScaffoldMessenger.of(context).showSnackBar(SnackBar(
        content: Text('暂无分类数据，请稍后重试'),
        duration: Duration(seconds: 2),
      ));
      return;
    }
    
    showModalBottomSheet(
      context: context,
      builder: (context) {
        return Container(
          padding: EdgeInsets.symmetric(vertical: 20),
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              Text('选择分类', style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold)),
              SizedBox(height: 10),
              Expanded(
                child: ListView.builder(
                  shrinkWrap: true,
                  itemCount: categoryList.length,
                  itemBuilder: (context, index) {
                    final category = categoryList[index];
                    return ListTile(
                      title: Text(category['name'] ?? '未知分类'),
                      trailing: selectedCategoryId == category['id']
                          ? Icon(Icons.check, color: Colors.blue)
                          : null,
                      onTap: () {
                        setState(() {
                          selectedCategoryId = category['id'];
                          selectedCategoryName = category['name'] ?? '';
                        });
                        Navigator.pop(context);
                      },
                    );
                  },
                ),
              ),
            ],
          ),
        );
      },
    );
  }
}
